<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019\6\16 0016
 * Time: 14:35
 */
namespace BigVideo\IMooc\Canvas;


class Canvas
{
    public $data;
    protected $decorators = [];

    /**
     * 初始化画布
     * @param int $width
     * @param int $height
     */
    public function init($width = 20,$height = 10){
        $data = [];
        for ($i = 0;$i < $height;$i++){
            for ($j = 0;$j < $width;$j++){
                $data[$i][$j] = "*";
            }
        }
        $this->data = $data;
    }

    /**
     * 添加装饰器
     * @param DrawDecorator $drawDecorator
     */
    public function addDecorator(DrawDecorator $drawDecorator){
        $this->decorators[] = $drawDecorator;
    }

    public function beforDraw(){
        /** @var DrawDecorator $decorator */
        foreach ($this->decorators as $decorator){
            $decorator->beforeDraw();
        }
    }

    public function afterDraw(){
        $decorators = array_reverse($this->decorators);
        /** @var DrawDecorator $decorator */
        foreach ($decorators as $decorator){
            $decorator->afterDraw();
        }
    }

    /**
     * 打印画布
     */
    public function draw(){
        $this->beforDraw();
        foreach ($this->data as $line) {
            foreach ($line as $char){
                echo $char;
            }
            echo "<br/>\n";
        }
        $this->afterDraw();
    }

    /**
     * 编辑画布
     * @param $a1
     * @param $a2
     * @param $b1
     * @param $b2
     */
    public function rect($a1,$a2,$b1,$b2){
        foreach ($this->data as $k1=>$line) {
            if($k1 < $a1 or $k1 > $a2)continue;
            foreach ($line as $k2=>$char){
                if($k2 < $b1 or $k2 > $b2)continue;
                $this->data[$k1][$k2] = '&nbsp;';
            }
        }
    }
}
















